<template>
  <div>
    <el-dialog :visible.sync="dialogOpen" title="操作退款" width="35%" center>
      <div class="flexBox">
        <p>
          <span>退款方式：</span>
          <el-select
              clearable
              v-model="data.payType"
              size="small"
              style="width: 200px"
              placeholder="请选择退款方式"
          >
            <el-option
                v-for="item in refundList"
                :key="item.payType"
                :label="item.refundName"
                :value="item.payType"
            />
          </el-select>
        </p>
        <p>
          <span>退款金额：</span>
          <el-input
              clearable
              v-model="data.refundAmount"
              size="small"
              style="width: 200px"
              placeholder="请输入退款金额"
          >
          </el-input>
        </p>
      </div>
      <div class="flexBox" v-if="data.payType == 2">
        <p>
          <span>银行卡号：</span>
          <el-input
              clearable
              v-model="data.bankCard"
              size="small"
              style="width: 200px"
              placeholder="请输入银行卡号"
          >
          </el-input>
        </p>
        <p>
          <span>持卡人：</span>
          <el-input
              clearable
              v-model="data.cardHolderName"
              size="small"
              style="width: 200px"
              placeholder="请输入持卡人姓名"
          >
          </el-input>
        </p>
      </div>
      <div class="flexBox">
        <div style="width: 280px"><span>表格截图：</span>
          <el-upload
              multiple
              class="uploader-wrap"
              :headers="headers"
              :action="`${$apiHost}/common/fileImgUrl`"
              :on-success="paySuc"
              :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
            <template #tip>
              <div class="img-wrap" style="display: flex">
                <div
                    v-for="(item, index) in tableScreenshotList"
                    :key="index"
                >
                  <el-image
                      :key="index"
                      :src="host + item"
                      :preview-src-list="
                            tableScreenshotList.map((img) => host + img)
                          "
                      class="img-item"
                      fit="cover"
                  >
                  </el-image>
                  <div @click="deletePic(index)">
                    <el-icon name="delete"></el-icon>
                  </div>
                </div>
              </div>
            </template>
          </el-upload>
        </div>
        <div style="width: 280px">
          <span style="width: 120px">财务付款凭证：</span>
          <div>
                  <span style="color: gray; font-size: 12px"
                  >(粘贴复制即可上传图片)</span
                  >
            <div class="div" style="display: flex; align-items: center">
              <div
                  v-for="(v, i) in payImgList"
                  style="
                        display: flex;
                        align-items: center;
                        margin-right: 10px;
                      "
                  :key="i"
              >
                <el-image
                    v-if="v"
                    :key="i"
                    style="width: 50px; height: 50px"
                    ref="preview"
                    :src="host + v"
                    :preview-src-list="[host + v]"
                >
                </el-image>
                <div @click="deleteImgVouchers(i)">
                  <el-icon name="delete"></el-icon>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="flexBox" style="justify-content: flex-start">
        <div style="width: 280px;margin-left: 15px">
          <span>套件明细：</span>
          <el-upload
              multiple
              class="uploader-wrap"
              :headers="headers"
              :action="`${$apiHost}/common/fileImgUrl`"
              :on-success="uploadSuccess"
              :file-list="fileList"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </div>
        <div style="width: 280px;margin-left: 20px" v-if="data.payType==1">
          <span style="width: 120px">二维码截图：</span>
          <el-upload
              multiple
              class="uploader-wrap"
              :headers="headers"
              :action="`${$apiHost}/common/fileImgUrl`"
              :on-success="qrcodeSuc"
              :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
            <template #tip>
              <div class="img-wrap" style="display: flex">
                <div v-for="(item, index) in qrcodeList" :key="index">
                  <el-image
                      :key="index"
                      :src="host + item"
                      :preview-src-list="
                            qrcodeList.map((img) => host + img)
                          "
                      class="img-item"
                      fit="cover"
                  >
                  </el-image>
                  <div @click="deletePic(index)">
                    <el-icon name="delete"></el-icon>
                  </div>
                </div>
              </div>
            </template>
          </el-upload>
        </div>
      </div>
      <div class="flexBox" style="justify-content: flex-start">
        <div style="margin-left: 20px">
          <span>备注：</span>
          <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="data.refundReason"
              style="width: 300px"
          >
          </el-input>
        </div>
      </div>
      <span slot="footer">
         <el-button @click="dialogOpen=false">取 消</el-button>
        <el-button type="primary" @click="onConfirm">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="refundDetail" title="退款明细" width="50%" center>
      <el-table :data="detailData" border
                height="calc(100vh - 250px)"
                :cellStyle="{ textAlign: 'center', 'font-size': '12px' }"
                :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
          fontSize: '12px'
        }">
        <el-table-column
            v-for="(col, index) in columns"
            :key="index"
            :prop="col.prop"
            :label="col.label"
        >
          <template v-slot:default="scope">
            <!-- {{ col.prop }} -->
            <div v-if="col.prop === 'qrCode'">
              <div style="display: flex">
                <div v-if="!scope.row.qrCode.length">无二维码截图</div>
                <div v-else>
                  <el-image
                      v-for="(item, index) in scope.row.qrCode"
                      :key="index"
                      :src="host + item"
                      style="width: 60px; height: 60px"
                      :preview-src-list="
                          scope.row.qrCode.map((img) => host + img)
                        "
                      class="img-item"
                      fit="cover"
                  >
                  </el-image>
                </div>
              </div>
            </div>
            <div v-else-if="col.prop === 'payVoucherStr'">
              <div style="display: flex">
                <div v-if="!scope.row.payVoucherStr.length">
                  无付款凭证截图
                </div>
                <div v-else>
                  <el-image
                      v-for="(item, index) in scope.row.payVoucher"
                      :key="index"
                      :src="host + item"
                      style="width: 60px"
                      :preview-src-list="
                          scope.row.payVoucher.map((img) => host + img)
                        "
                      class="img-item"
                      fit="cover"
                  >
                  </el-image>
                </div>
              </div>
            </div>
            <div v-else-if="col.prop === 'tableScreenshotStr'">
              <div style="display: flex">
                <el-image
                    v-for="(item, index) in scope.row.tableScreenshot"
                    :key="index"
                    :src="host + item"
                    style="width: 60px"
                    :preview-src-list="
                        scope.row.tableScreenshot.map((img) => host + img)
                      "
                    class="img-item"
                    fit="cover"
                >
                </el-image>
              </div>
            </div>
            <div v-else-if="col.prop === 'excel'">
              <div style="display: flex">
                <el-link
                    style="color: aqua; text-decoration: underline"
                    @click="inToUrl(scope.row.excelPath)"
                >{{ scope.row.excel }}
                </el-link
                >
              </div>
            </div>
            <p v-else>
              {{ scope.row[col.prop] }}
            </p>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "refundDialog",
  data() {
    return {
      dialogOpen: false,
      refundDetail: false,
      refundId: "",
      qrcodeList: [],
      detailData: [],
      data: {
        orderId: this.refundId,
        payType: '', // 退款方式
        excel: null, // 文件流对象
        excelPath: '', // 文件流上传路径
        refundAmount: '', // 退款金额
        refundReason: '', // 备注退款原因
        bankCard: '', // 输入银行卡号
        cardHolderName: '', // 持卡人姓名
        qrCode: [], // 二维码
        payVoucherStr: '', // 付款凭证截图
        tableScreenshotStr: '', // 表格凭证截图
      },
      host: this.$imgHost,
      isShow: false,
      showDetail: false,
      tableScreenshotList: [], // 表格截图
      payImgList: [], // 财务付款凭证
      detailTitle: '退款明细',
      fileList: [], // 表格截图回显
      fileList1: [], // 二维码截图回显
      refundList: [
        {
          payType: 1,
          refundName: '微信/支付宝二维码',
        },
        {
          payType: 2,
          refundName: '银行卡支付',
        },
      ],
      textarea: '',
      detailList: [], // 退款明细表格
      columns: [
        {prop: 'orderId', label: '订单ID'},
        {prop: 'payType', label: '退款方式'},
        {prop: 'refundAmount', label: '退款金额'},
        {prop: 'excel', label: '套件明细Excel'},
        {prop: 'bankCard', label: '银行卡号'},
        {prop: 'cardHolderName', label: '持卡人姓名'},
        {prop: 'qrCode', label: '二维码截图'},
        {prop: 'payVoucherStr', label: '付款凭证截图'},
        {prop: 'tableScreenshotStr', label: '表格截图'},
        {prop: 'refundReason', label: '备注'},
      ],
      tableScreenshot: [], // 表格图片预览
      payVoucher: [], // 凭证预览
      qrCode: [], // 二维码预览
    }
  },
  created() {
    document.addEventListener('paste', this.handlePaste)
    this.payImgList = []
  },
  computed: {
    headers() {
      const token = this.$quinn.getStorage('token')
      return {
        token,
      }
    },
  },
  methods: {
    handleOpen(val) {
      this.refundId = val.id
      this.data = this.$options.data.call(this).data
      this.dialogOpen = true
    },
    paySuc(res) {
      if (res.code == 200 && res.result) {
        this.tableScreenshotList.push(res.result[0])
        this.data.tableScreenshotStr = this.tableScreenshotList.join(',')
      }
    },
    deletePic(i) {
      this.tableScreenshotList.splice(i, 1)
      this.qrcodeList.splice(i, 1)
    },
    qrcodeSuc(res) {
      if (res.code == 200 && res.result) {
        this.qrcodeList.push(res.result[0])
        this.data.qrCode = this.qrcodeList.join(',')
      }
    },
    deleteImgVouchers(i) {
      this.payImgList.splice(i, 1)
    },
    handleCancel() {
      this.isShow = false
    },
    handlePreview(file) {
      console.log(file)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handleExceed(files, fileList) {
      this.$message.warning(
          `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
              files.length + fileList.length
          } 个文件`
      )
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    preview() {
      const {id} = this.row
      let url = `${LOGIN_PATH}#/quoteExport?type=preview&id=${id}&token=${this.token}`
      window.open(url, '_blank', 'height=667 ,width=375,top=200,left=400')
    },
    handlePaste(event) {
      if (!this.dialogOpen) return console.log("1")
      const clipboardData = event.clipboardData
      console.log('clipboardData', clipboardData)
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file) // 处理文件上传逻辑
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
          .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: window.$quinn.getStorage('token'),
            },
          })
          .then((response) => {
            this.payImgList.push(response.data.result[0])
            // console.log('this.payImgList', this.payImgList)
            this.data.payVoucherStr = this.payImgList.join(',')
          })
          .catch((error) => {
          })
    },
    uploadSuccess(response, file, fileList) {
      // response, file, fileList
      // console.log('response', response)
      // console.log('file', file)
      // console.log('fileList', fileList)
      if (response.code == 200 && response.result) {
        this.fileList = fileList
        this.data.excelPath = response.result[0] // 文件流上传路径
        this.data.excel = file.raw // 文件流对象
      }
    },
    qrcodeUpload(response, file, fileList) {
      // response, file, fileList
      // console.log('response', response)
      // console.log('file', file)
      // console.log('fileList', fileList)
      if (response.code == 200 && response.result) {
        this.fileList = fileList
        this.data.excelPath = response.result[0] // 文件流上传路径
        this.data.excel = file.raw // 文件流对象
      }
    },
    inToUrl(el) {
      window.open('https:' + el)
    },
    async lookDetail(orderId) {
      this.showDetail = true
      if (this.showDetail) {
        const data = {orderId: 104819}
        const res = await this.$api.refundGetCustomerRefund(data)
        if (res.length) {
          const qrCodeList = []
          res.forEach((el) => {
            if (el.qrCode) {
              qrCodeList.push(el.qrCode)
              el.qrCode = qrCodeList
              console.log('el.qrCode', el.qrCode)
            } else {
              el.qrCode = []
            }

            if (el.payType == 1) {
              el.payType = '微信/支付宝二维码'
            } else if (el.payType == 2) {
              el.payType = '银行卡支付'
            }
            // 表格处理
            if (el.excelPath) {
              // console.log('el.excelPath', el.excelPath)
              const arrTemp = el.excelPath.split('/')
              el.excel = arrTemp[3].substring(14) // 表格名称
              console.log('el.excelName', el.excel)
            }
          })
          this.detailList = res
          console.log('this.detailList', res)
        }

        // this.tableScreenshot = res[0].tableScreenshot
        // this.payVoucher = res[0].payVoucher
        // this.qrCode = res[0].qrCode || []
      }
    },
    async onConfirm() {
      const {
        // orderId,
        payType,
        excel,
        excelPath,
        refundAmount,
        refundReason,
        bankCard,
        cardHolderName,
        qrCode,
        payVoucherStr,
        tableScreenshotStr,
      } = this.data
      // if (!orderId) return this.$message.error('无订单ID!')
      if (!payType) return this.$message.error('请选择退款方式!')
      if (!excel && !excelPath) return this.$message.error('请选择上传文件!')
      if (!refundAmount) return this.$message.error('请选择退款金额!')
      if (payType == 2) {
        if (!bankCard) return this.$message.error('请选择退款账号!')
        if (!cardHolderName) return this.$message.error('请选择执卡人姓名!')
      } else if (payType == 1) {
        if (!qrCode) return this.$message.error('请上传退款二维码!')
      }
      if (!payVoucherStr) return this.$message.error('请上传付款凭证!')
      if (!tableScreenshotStr) return this.$message.error('请上传表格截图!')
      const formData = new FormData()
      formData.append('orderId', this.refundId)
      formData.append('payType', payType)
      formData.append('excel', excel)
      formData.append('excelPath', excelPath)
      formData.append('refundAmount', refundAmount)
      formData.append('refundReason', refundReason)
      formData.append('bankCard', bankCard)
      formData.append('cardHolderName', cardHolderName)
      formData.append('qrCode', qrCode)
      formData.append('payVoucherStr', payVoucherStr)
      formData.append('tableScreenshotStr', tableScreenshotStr)
      const res = await this.$api.refundAddCustomerRefund(formData)
      if (res == 1) {
        this.$message.success('退款成功!')
        this.dialogVisible = false
      }
    },
    checkRefundDetail(row) {
      this.$api.refundGetCustomerRefund({orderId: row.id}).then(res => {
        if (res.length == 0) {
          this.$message.warning('没有退款记录。')
        } else {
          this.refundDetail = true
          this.detailData = res
        }
      })

    }
  }
}
</script>

<style scoped lang="less">
/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

.flexBox {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;

  span {
    width: 80px;
    display: inline-block;
  }
}
</style>